package com.it.myd.help;

import java.io.IOException;
import java.nio.file.*;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.nio.file.StandardWatchEventKinds.*;

public class FileWatcherExample {
    private static String outFileContent;

    public static String getSharedOutFileContent() {
        return outFileContent;
    }

    public static void setSharedOutFileContent(String Content) {
        outFileContent = Content;
    }


    public static void main(String[] args){
        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();


            Path path = Paths.get("//opt/mc");
            Path sourceFile = path.resolve("nohup.out");
            Path targetFile = path.resolve("nohup_temp.out");

            // 注册目录以及感兴趣的事件类型
            path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

            while (true) {
                WatchKey key = watchService.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();

                    // 获取触发事件的文件名
                    Path eventFile = (Path) event.context();

                    // 检查事件是否与特定文件相关
                    if (eventFile.equals(sourceFile.getFileName())) {
                        System.out.println(kind.name() + ": " + eventFile);
                        // 执行与特定文件相关的操作
                        if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            copyFile(sourceFile, targetFile);
                            String outFileContent = ReadOutFileHelper.getOutFileContent("//opt/mc/nohup_temp.out");
                            if (StringHelper.isNotNull(outFileContent)) {
                                setSharedOutFileContent("");
                                setSharedOutFileContent(outFileContent);
                            }
                        }
                    }
                }

                // 重置WatchKey
                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void copyFile(Path source, Path target) {
        try {
            // 使用REPLACE_EXISTING选项，如果目标文件已存在，则替换它
            Files.copy(source, target, REPLACE_EXISTING);
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
